import time

from sqlalchemy import desc, asc
from sqlalchemy.sql import text

from ..model.label_model import LabelModel
from ..model.label_log import LabelLogModel
from hzb.database import db


class LabelLogic(object):

    def __init__(self):
        pass

    def get_labels(self, user_id):
        _result = list()
        _datas = LabelModel.query.order_by(desc(LabelModel.create_time))\
                        .filter_by(user_id=user_id)\
                        .all()
        for _data in _datas:
            _result.append(_data.to_dict())
        return _result
        pass

    def set_run_label(self, user_id, label_name):
        _result = 0
        # 应该只有一个标签页checked=True
        _label_model = LabelModel.query.filter_by(user_id=user_id, checked=True).first()
        if _label_model is not None:
            _label_model.checked = False
            db.session.commit()
        _label_model = LabelModel.query.filter_by(user_id=user_id, label_name=label_name).first()
        if _label_model is not None:
            _result = int(time.time())
            _label_model.choose_time = _result
            _label_model.checked = True
            db.session.commit()
            # 新增log
            _log = LabelLogModel()
            _log.label_name = label_name
            _log.user_id = user_id
            _log.create_time = int(time.time())
            db.session.add(_log)
            db.session.commit()
        return _result
        pass

    def add_label(self, user_id, label_name):
        try:
            _model = LabelModel()
            _model.user_id = user_id
            _model.label_name = label_name
            _model.create_time = int(time.time())
            _model.checked = False
            _model.choose_time = 0
            db.session.add(_model)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            return False
        pass

    def del_labels(self, user_id, _label_names):
        try:
            for _label_name in _label_names:
                print("del_labels", _label_name)
                _model = LabelModel.query.filter_by(user_id=user_id, label_name=_label_name).first()
                _model.user_id = user_id
                _model.label_name = _label_name
                db.session.delete(_model)
                db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            return False
        pass

    def get_24_time_record_labels(self, user_id):
        _result = list()
        user_id = user_id
        begin_time = int(time.time() - 86400)
        _labels = LabelLogModel.query.filter(text("user_id=:user_id and create_time>=:begin_time"))\
            .params(user_id=user_id, begin_time=begin_time).order_by(desc(LabelLogModel.create_time)).all()
        for _label in _labels:
            _item = dict()
            _item['label_name'] = _label.label_name
            # 转换成localtime
            time_local = time.localtime(_label.create_time)
            # 转换成新的时间格式(2016-05-05 20:28:54)
            dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
            _item['time_string'] = dt
            _result.append(_item)
        return _result


    def get_record_by_time(self, user_id, begin_time, end_time):
        _result = list()
        user_id = user_id
        _labels = LabelLogModel.query.filter(text("user_id=:user_id and (create_time>=:begin_time "
                                                  "or create_time<=:end_time)"))\
            .params(user_id=user_id, begin_time=begin_time, end_time=end_time)\
            .order_by(asc(LabelLogModel.create_time)).all()

        if _labels is not None and _labels[0] is not None:
            _first = LabelLogModel.query.filter(LabelLogModel.id < _labels[0].id).order_by(desc(LabelLogModel.id)).first()
            if _first is not None:
                _labels.insert(0, _first)

        if _labels is not None:
            _last = LabelLogModel.query.filter(LabelLogModel.id > _labels[len(_labels)-1].id)\
                .order_by(asc(LabelLogModel.id)).first()
            if _last is not None:
                _labels.append(_last)
            else:
                _last = LabelLogModel()
                _last.user_id = user_id
                _last.label_name = _labels[len(_labels) - 1].label_name
                _last.create_time = int(time.time())
                _labels.append(_last)

        # 所有的标签统计
        _label_dict = dict()
        for i in range(0, len(_labels)-1):
            _item = _labels[i]
            _next_item = _labels[i+1]
            if _label_dict.get(_item.label_name) is None:
                _label_dict[_item.label_name] = 0
            # print("_label_dict", _item.label_name, _item.create_time, _pre_item.label_name, _pre_item.create_time, _item.create_time - _pre_item.create_time)
            _label_dict[_item.label_name] += (_next_item.create_time - _item.create_time)
            pass
        for k, v in _label_dict.items():
            _item = dict()
            _item['name'] = k
            _item['value'] = v
            _result.append(_item)
        # print(_label_dict)
        return _result

    def setDefaultLabel(self, user_id):
        # 工作，娱乐，在路上
        _work_label = LabelModel()
        _work_label.create_time = int(time.time())
        _work_label.label_name = "工作"
        _work_label.user_id = user_id
        _work_label.checked = False
        _work_label.choose_time = 0
        db.session.add(_work_label)
        _recreation_label = LabelModel()
        _recreation_label.create_time = int(time.time())
        _recreation_label.label_name = "娱乐"
        _recreation_label.user_id = user_id
        _recreation_label.checked = False
        _recreation_label.choose_time = 0
        db.session.add(_recreation_label)
        _way_label = LabelModel()
        _way_label.create_time = int(time.time())
        _way_label.label_name = "在路上"
        _way_label.user_id = user_id
        _way_label.checked = False
        _way_label.choose_time = 0
        db.session.add(_way_label)
        db.session.commit()
        pass
    pass
